<template>
	<div class="content">
		<div class="pageSearchView">
			<SearchForm v-model="searchParam" :fields="searchFields" :handleSearch="handleSearch" />
		</div>

		<div class="pageTableView">
			<el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-click="handleClick">
				<el-tab-pane label="未完成" name="WAITING">
					<div class="pageTableMenuView">
						<div class="pageTableTitle">
							列表信息
							<el-icon>
								<house-icon />
							</el-icon>
						</div>
						<div class="pageTableButView">
							<el-button :icon="Plus" @click="handleAdd">新建</el-button>
						</div>
					</div>
					<Unfinished :paginationParams="paginationParams" :pageTotal="pageTotal" :taskNoPage="taskNoPage"
											:onSubmit="onSubmit" :fetchPage="fetchPage" :equipmentData="equipmentData"
											:handleSizeChange="handleSizeChange" :handleCurrentChange="handleCurrentChange"
											:handleEdit="handleEdit"
											:handleDel="handleDel" :faultTypeOptions="faultTypeOptions" />
				</el-tab-pane>
				<el-tab-pane label="已完成" name="FIXED">
					<div class="pageTableMenuView">
						<div class="pageTableTitle">
							列表信息
							<el-icon>
								<house-icon />
							</el-icon>
						</div>
					</div>
					<Finish :paginationParams="paginationParams" :pageTotal="pageTotal" :taskNoPage="taskNoPage"
									:onSubmit="onSubmit" :fetchPage="fetchPage" :equipmentData="equipmentData"
									:handleSizeChange="handleSizeChange" :faultTypeOptions="faultTypeOptions"
									:handleCurrentChange="handleCurrentChange" />
				</el-tab-pane>
			</el-tabs>
		</div>

		<!-- 新建/编辑弹框 -->
		<el-dialog v-model="dialogVisible" :title="dialogTitle" width=500>

			<el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
				<el-form-item label="维修名称" required prop="name" v-if="['add', 'edit'].includes(dialogType)">
					<el-input v-model="form.name" placeholder="请输入维修名称" style="width: 300px" />
				</el-form-item>
				<el-form-item label="维修编码" required prop="code" v-if="['add', 'edit'].includes(dialogType)">
					<el-input v-model="form.code" placeholder="请输入维修编码" style="width: 300px" />
				</el-form-item>
				<el-form-item label="维修工装" prop="equipmentId" v-if="['add', 'edit'].includes(dialogType)">
					<el-select v-model="form.equipmentId" placeholder="请选择维修工装" style="width: 300px">
						<el-option v-for="item in equipmentData" :key="item.id" :label="item.equipmentName" :value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="实施角色" prop="executeUserId" v-if="['add', 'edit'].includes(dialogType)">
					<el-select v-model="form.executeUserId" placeholder="请选择执行人" filterable style="width: 300px">
						<el-option v-for="item in userPersonData" :key="item.id" :label="item.nickname" :value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="维修过程" required prop="malfunctionProcedure" v-if="dialogType === 'perform'">
					<el-input v-model="form.malfunctionProcedure" placeholder="请输入维修过程" style="width: 300px" />
				</el-form-item>
				<el-form-item label="故障类型" prop="malfunctionId">
					<el-tree-select v-model="form.malfunctionId" :data="faultData" check-strictly clearable
													:render-after-expand="false" :props="{ value: 'id', label: 'name', children: 'children' }"
													placeholder="请选择故障类型" style="width: 300px" />
				</el-form-item>
				<el-form-item label="故障内容" prop="description" v-if="['add', 'edit'].includes(dialogType)">
					<el-input v-model="form.description" type="textarea" placeholder="请输入故障内容" style="width: 300px"></el-input>
				</el-form-item>
				<el-form-item label="备件更换情况" prop="replacementPart" v-if="['perform'].includes(dialogType)">
					<el-input v-model="form.replacementPart" type="textarea" placeholder="请输入备件更换情况" style="width: 300px">
					</el-input>
				</el-form-item>
				<el-form-item label="维修结果" prop="result" v-if="dialogType === 'perform'">
					<el-select v-model="form.result" placeholder="请选择维修结果" clearable style="width: 300px">
						<el-option v-for="(item, index) of result" :key="index" :label="item.value" :value="item.label" />
					</el-select>
				</el-form-item>
			</el-form>

			<template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
			</template>
		</el-dialog>
	</div>
</template>
<script setup>
import SearchForm from '@/components/SearchForm.vue';
import { useToolData } from '@/hooks/baseData/tooling';
import axiosInstance from '@/utils/http/api';
import { Delete, Edit, Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { computed, onMounted, ref } from 'vue';
import Unfinished from './unfinished.vue';
import Finish from './finish.vue';
import {
	maintenanceOrderAdd,
	equipmentAll,
	maintenanceOrderPage,
	maintenanceOrderUpdate,
	maintenanceMalfunctionAll
} from '@/api/device/maintain';
import { userPersonAll } from '@/api/device/creatPlan';

const activeName = ref('WAITING');
const searchParam = ref({});
const searchFields = ref([
	{
		name: 'name',
		label: '维修名称',
		component: 'input',
		placeholder: '',
		class: '!w-[350px]'
	}
]);
const pageTotal = ref(0);
const taskNoPage = ref([]);
const equipmentData = ref([]);
const faultData = ref([]);
const paginationParams = ref({ pageSize: 10, current: 1 });
const dialogVisible = ref(false);
const dialogTitle = ref('新建');
const dialogType = ref('add');
const form = ref({
	equipmentId: '',
	executeUserId: '',
	malfunctionId: [],
	description: ''
});
const result = ref([
	{ label: '结果1', value: '1' }
]);
const rules = ref({
	equipmentId: [{ required: true, message: '请选择维修工装', trigger: 'blur' }],
	executeUserId: [{ required: true, message: '请输入实施角色', trigger: 'blur' }],
	malfunctionId: [{ required: true, message: '请选择故障类型', trigger: 'blur' }],
	description: [{ required: true, message: '请输入故障内容', trigger: 'blur' }]
});
const faultTypeOptions = ref([]);

onMounted(() => {
	fetchPage();
	fetchAll();
	fetchFaultTypes();
});
const transformToTree = (data) => {
	const map = new Map();
	const tree = [];

	data.forEach(item => {
		map.set(item.id, { ...item, children: [] });
	});

	data.forEach(item => {
		if (item.parentId === '0') {
			tree.push(map.get(item.id));
		} else {
			const parent = map.get(item.parentId);
			if (parent) {
				parent.children.push(map.get(item.id));
			}
		}
	});

	return tree;
};

const userPersonData = ref([])
const fetchAll = () => {
	userPersonAll({}).then(res => {
		userPersonData.value = res.data;
	});
	equipmentAll({}).then(res => {
		equipmentData.value = res.data;
	});
	maintenanceMalfunctionAll({}).then(res => {
		faultData.value = transformToTree(res.data);
		faultTypeOptions.value = res.data;
	});
};

const fetchPage = (params) => {
	maintenanceOrderPage({
		...paginationParams.value,
		...searchParam.value,
		orderStatus: activeName.value,
		...params,
		type: 2

	}).then(res => {
		taskNoPage.value = res.data.records;
		pageTotal.value = res.data.total;
	});
};
const handleEdit = (row, type) => {
	if (type) {
		dialogTitle.value = '维修任务完成确认';
		dialogVisible.value = true;
		form.value = { ...row, orderStatus: 'FIXED' };
		dialogType.value = 'perform';
	} else {
		dialogTitle.value = '修改';
		dialogVisible.value = true;
		form.value = { ...row };
		dialogType.value = 'edit';

	}

};
const handleDel = () => {

};
const handleAdd = () => {
	dialogTitle.value = '新建';
	dialogVisible.value = true;
	dialogType.value = 'add';
	form.value = {
		equipment: '',
		executeUserId: '',
		faultType: [],
		description: ''

	};
};

const handleSearch = () => {
	fetchPage();
};

const handleClick = (tab, event) => {
	console.log(tab.props.name, tab.props, 'tab, event');
	fetchPage({ orderStatus: tab.props.name });
};

const onSubmit = (params, callback) => {
	maintenanceOrderUpdate(params).then(res => {
		if (res.code === 200) {
			ElMessage.success('任务已完成');
			fetchPage();
			callback();
		} else {
			ElMessage.error(res.message);
		}
	});
};

const handleSizeChange = (val) => {
	paginationParams.value.pageSize = val;
	fetchPage();
};

const handleCurrentChange = (val) => {
	paginationParams.value.current = val;
	fetchPage();
};

const fetchFaultTypes = () => {

};

const handleSubmit = () => {
	const data = { ...form.value, type: 2 };
	const url = data?.id ? dialogType.value === 'perform' ?
		maintenanceOrderUpdate : maintenanceOrderUpdate : maintenanceOrderAdd;

	url(data).then(response => {
		if (response.code === 200) {
			if (data?.id) {
				if (dialogType.value === 'perform') {
					ElMessage.success('任务已完成');

				} else {
					ElMessage.success('更新成功');
				}

			} else {
				ElMessage.success('添加成功');
			}
			dialogVisible.value = false;
			fetchPage();
		} else {
			ElMessage.error(response.message);
		}
	});


};
</script>

<style scoped>
/* 样式可以根据需要调整 */
</style>